<template>
  <Main @create="create" @upload="upload" :is-upload="true">
    <template #search>
      <Form
        :form-data="formData"
        :control-list="controlList"
        @search="search"
      ></Form>
    </template>
    <template #table>
      <el-table
        :data="tableData"
        :border="true"
        v-loading="loading"
        height="100%"
      >
        <el-table-column
          v-for="tableColumn of tableColumnList"
          :key="tableColumn.uuid"
          :label="tableColumn.label"
          :prop="tableColumn.prop"
          :type="tableColumn.type"
          :width="tableColumn.width"
          header-align="center"
          align="center"
        >
          <template v-if="tableColumn.label === '操作'" #default="{ row }">
            <Operate
              v-if="canEdit"
              @remove="() => remove(row)"
              @edit="() => edit(row)"
            ></Operate>
          </template>
          <template
            v-else-if="tableColumn.label === '是否装修'"
            #default="{ row }"
          >
            <el-tag :type="row.decorationStatus === '1' ? 'danger' : 'info'">{{
              row.decorationStatus === "1" ? "是" : "否"
            }}</el-tag>
          </template>
          <template
            v-else-if="tableColumn.label === '是否常住'"
            #default="{ row }"
          >
            <el-tag :type="row.liveStatus === '1' ? 'danger' : 'info'">{{
              row.liveStatus === "1" ? "是" : "否"
            }}</el-tag>
          </template>
          <template
            v-else-if="tableColumn.label === '是否欠费'"
            #default="{ row }"
          >
            <el-tag :type="row.oweStatus === '1' ? 'danger' : 'info'">{{
              row.oweStatus === "1" ? "是" : "否"
            }}</el-tag>
          </template>
        </el-table-column>
      </el-table>
    </template>
    <template #pagination>
      <Pagination
        :pagination="pagination"
        @change="paginationChange"
      ></Pagination>
    </template>
  </Main>
</template>
<script>
import Main from "@/views/component/main/index.vue";
import Form from "@/views/component/form/index.vue";
import Pagination from "@/views/component/pagination/index.vue";
import {
  startEndEmptyValidator,
  stringEmptyValidator,
} from "@/utils/validator/index";
import Operate from "@/views/component/operate/index.vue";
import {
  getOwnerByPaginationAndQuestion,
  removeOwnerByUuid,
} from "@/api/owner";
import { uploadOwner, getOwnerByAll } from "@/api/owner";
import { flushPage } from "@/utils/page";
import {
  showFlushNg,
  showRemoveNg,
  showRemoveOk,
  showUploadOk,
  showUploadNg,
  showDataOk,
  showDataNg,
} from "@/utils/message";
import { getWorkbook, getWorksheet, getAllRow } from "@/utils/excel";
import _ from "lodash";
import { getQuestionConfig } from "@/api/config";

function getAllMonth() {
  let result = [];
  for (let i = 1; i <= 12; i++) {
    let item = {
      label: `${i}月`,
      value: `${i}月`,
    };
    result.push(item);
  }
  return result;
}

export default {
  name: "Owner",
  computed: {
    canEdit() {
      return (
        this.$store.state.user.roles.includes("编辑业主") ||
        this.$store.state.user.roles.includes("超级管理员")
      );
    },
  },
  components: { Operate, Pagination, Main, Form },
  beforeRouteEnter(to, from, next) {
    next(async (vm) => {
      await vm.getQuestionConfig();
      await vm.getOwnerByPaginationAndQuestion();
      await vm.getOwnerByAll();
      vm.setControlList();
    });
  },
  methods: {
    setControlList() {
      this.controlList = [
        {
          type: "select",
          label: "组团",
          prop: "groupName",
          clearable: true,
          change: (event) => {
            this.formData = {
              uuid: "",
              name: "",
              groupName: event ?? "",
              address: "",
              homeType: "",
              homeStatus: "",
              decorationStatus: "",
              liveStatus: "",
              oweStatus: "",
              ownerType: "",
              payStyle: "",
              payMonth: [],
              departmentQuestion: [[]],
              ownerQuestion: "",
            };
            if (!this.formData.groupName) {
              this.baseOwner = this.allOwner;
            } else {
              this.baseOwner = this.allOwner.filter((owner) => {
                return owner.groupName === this.formData.groupName;
              });
            }
          },
          optionList: [
            {
              label: "超豪样板间",
              value: "超豪样板间",
            },
            {
              label: "峰景",
              value: "峰景",
            },
            {
              label: "凤鸣翠岭",
              value: "凤鸣翠岭",
            },
            {
              label: "观山",
              value: "观山",
            },
            {
              label: "观山二期",
              value: "观山二期",
            },
            {
              label: "山居小墅",
              value: "山居小墅",
            },
            {
              label: "山语",
              value: "山语",
            },
            {
              label: "商铺",
              value: "商铺",
            },
            {
              label: "桐林人家",
              value: "桐林人家",
            },
            {
              label: "玺园",
              value: "玺园",
            },
            {
              label: "映山",
              value: "映山",
            },
            {
              label: "锦绣江山",
              value: "锦绣江山",
            },
          ],
        },
        {
          type: "autocomplete",
          label: "姓名",
          prop: "name",
          clearable: true,
          width: "300px",
          change: (event) => {
            this.formData.uuid = "";
            let owner = this.baseOwner.filter((owner) => {
              return owner.name === (!event.value ? event : event?.name);
            });
            if (owner.length === 1) {
              owner = owner[0];
              this.formData = { ...owner, ownerQuestion: "" };
            } else {
              this.formData = {
                uuid: "",
                name: !event.value ? event : event?.name,
                groupName: this.formData.groupName,
                address: "",
                homeType: "",
                homeStatus: "",
                decorationStatus: "",
                liveStatus: "",
                oweStatus: "",
                ownerType: "",
                payStyle: "",
                payMonth: [],
                departmentQuestion: [[]],
                ownerQuestion: "",
              };
            }
          },
          query: (queryString, cb) => {
            let tempOwnerList = [];
            if (!this.formData.address) {
              if (!this.formData.name) {
                tempOwnerList = this.baseOwner;
              } else {
                tempOwnerList = this.baseOwner.filter((owner) => {
                  return owner.name.includes(this.formData.name);
                });
              }
            } else {
              tempOwnerList = this.baseOwner.filter((owner) => {
                return owner.address === this.formData.address;
              });
              if (tempOwnerList.length === 0) {
                tempOwnerList = [];
              } else {
                tempOwnerList = this.baseOwner.filter((owner) => {
                  return (
                    owner.address === this.formData.address &&
                    owner.name.includes(this.formData.name)
                  );
                });
              }
            }
            tempOwnerList = tempOwnerList
              .sort((a, b) => {
                return a.name.localeCompare(b.name);
              })
              .map((owner) => {
                return {
                  ...owner,
                  label: owner.name,
                  value: { address: owner.address, name: owner.name },
                };
              });
            cb(tempOwnerList);
          },
          rule: [
            {
              trigger: ["blur", "change"],
              validator: (rule, value, callback) => {
                if (value.length === 0) {
                  return callback();
                }
                let index = this.allOwner.findIndex((owner) => {
                  return owner.name === value;
                });
                if (index === -1) {
                  return callback("未找到业主");
                }
                return callback();
              },
            },
          ],
        },
        {
          type: "autocomplete",
          label: "路址",
          prop: "address",
          clearable: true,
          width: "350px",
          change: (event) => {
            this.formData.uuid = "";
            let owner = this.baseOwner.filter((owner) => {
              return owner.address === (!event.value ? event : event?.address);
            });
            if (owner.length === 1) {
              owner = owner[0];
              this.formData = { ...owner, ownerQuestion: "" };
            } else {
              this.formData = {
                uuid: "",
                name: "",
                groupName: this.formData.groupName,
                address: !event.value ? event : event?.address,
                homeType: "",
                homeStatus: "",
                decorationStatus: "",
                liveStatus: "",
                oweStatus: "",
                ownerType: "",
                payStyle: "",
                payMonth: [],
                departmentQuestion: [[]],
                ownerQuestion: "",
              };
            }
          },
          query: (queryString, cb) => {
            let tempOwnerList = [];
            if (!this.formData.name) {
              if (!this.formData.address) {
                tempOwnerList = this.baseOwner;
              } else {
                tempOwnerList = this.baseOwner.filter((owner) => {
                  return owner.address.includes(this.formData.address);
                });
              }
            } else {
              tempOwnerList = this.baseOwner.filter((owner) => {
                return owner.name === this.formData.name;
              });
              if (tempOwnerList.length === 0) {
                tempOwnerList = [];
              } else {
                tempOwnerList = this.baseOwner.filter((owner) => {
                  return owner.name === this.formData.name;
                });
              }
            }
            tempOwnerList = tempOwnerList
              .sort((a, b) => {
                return a.address.localeCompare(b.address);
              })
              .map((owner) => {
                return {
                  ...owner,
                  label: owner.address,
                  value: { address: owner.address, name: owner.name },
                };
              });
            cb(tempOwnerList);
          },
          rule: [
            {
              trigger: ["blur", "change"],
              validator: (rule, value, callback) => {
                if (value.length === 0) {
                  return callback();
                }
                let index = this.baseOwner.findIndex((owner) => {
                  return owner.address === value;
                });
                if (index === -1) {
                  return callback("未找到路址");
                }
                return callback();
              },
            },
          ],
        },
        {
          type: "select",
          label: "房屋类型",
          prop: "homeType",
          clearable: true,
          change: (event) => {
            this.formData.homeType = event ?? "";
          },
          optionList: [
            {
              label: "住宅",
              value: "住宅",
            },
            {
              label: "商铺",
              value: "商铺",
            },
            {
              label: "车库",
              value: "车库",
            },
            {
              label: "车位",
              value: "车位",
            },
          ],
          rule: [
            {
              trigger: ["blur", "change"],
              validator: startEndEmptyValidator,
            },
          ],
        },
        {
          type: "select",
          label: "房屋状态",
          prop: "homeStatus",
          clearable: true,
          change: (event) => {
            this.formData.homeStatus = event ?? "";
          },
          optionList: [
            {
              label: "已售已收楼",
              value: "已售已收楼",
            },
            {
              label: "应收未收楼",
              value: "应收未收楼",
            },
            {
              label: "已售未到合同收楼期",
              value: "已售未到合同收楼期",
            },
            {
              label: "未收空置",
              value: "未收空置",
            },
          ],
        },
        {
          type: "select",
          label: "业主类别",
          prop: "ownerType",
          clearable: true,
          change: (event) => {
            this.formData.ownerType = event ?? "";
          },
          optionList: [
            {
              label: "A 友好关系户",
              value: "A 友好关系户",
            },
            {
              label: "B 一般客户",
              value: "B 一般客户",
            },
            {
              label: "E 意见客户",
              value: "E 意见客户",
            },
          ],
        },
        {
          type: "select",
          label: "缴费习惯",
          prop: "payStyle",
          clearable: true,
          change: (event) => {
            this.formData.payStyle = event ?? "";
          },
          optionList: [
            {
              label: "月度缴费",
              value: "月度缴费",
            },
            {
              label: "季度缴费",
              value: "季度缴费",
            },
            {
              label: "半年缴费",
              value: "半年缴费",
            },
            {
              label: "全年缴费",
              value: "全年缴费",
            },
          ],
        },
        {
          type: "multipleSelect",
          label: "缴费月份",
          prop: "payMonth",
          clearable: true,
          change: (event) => {
            this.formData.payMonth = event ?? "";
          },
          optionList: getAllMonth(),
        },
        {
          type: "radio-group",
          label: "是否装修",
          prop: "decorationStatus",
          progress: 0,
          change: (event) => {
            this.formData.decorationStatus = event ?? "";
          },
          radioList: [
            {
              label: "忽略",
              value: "",
            },
            {
              label: "是",
              value: "1",
            },
            {
              label: "否",
              value: "2",
            },
          ],
        },
        {
          type: "radio-group",
          label: "是否常住",
          prop: "liveStatus",
          progress: 0,
          change: (event) => {
            this.formData.liveStatus = event ?? [];
          },
          radioList: [
            {
              label: "忽略",
              value: "",
            },
            {
              label: "是",
              value: "1",
            },
            {
              label: "否",
              value: "2",
            },
          ],
        },
        {
          type: "radio-group",
          label: "是否欠费",
          prop: "oweStatus",
          progress: 0,
          change: (event) => {
            this.formData.roleUuidList = event ?? [];
          },
          radioList: [
            {
              label: "忽略",
              value: "",
            },
            {
              label: "是",
              value: "1",
            },
            {
              label: "否",
              value: "2",
            },
          ],
        },
        {
          type: "cascaderList",
          optionList: this.questionConfig,
          label: "部门问题",
          prop: "departmentQuestion",
          width: "400px",
          listAdd: (index) => {
            this.formData.departmentQuestion.push([]);
          },
          listRemove: (index) => {
            if (this.formData.departmentQuestion.length === 1) {
              return;
            }
            this.formData.departmentQuestion.splice(index, 1);
          },
          change: ({ event, index }) => {
            this.$set(this.formData.departmentQuestion, index, event);
          },
        },
      ];
    },
    async getQuestionConfig() {
      let result = await getQuestionConfig();
      this.questionConfig = result.data;
    },
    async getOwnerByAll() {
      try {
        let result = await getOwnerByAll();
        this.allOwner = result.data.list.map((owner) => {
          return {
            ...owner,
            payMonth: JSON.parse(owner.payMonth),
            departmentQuestion: JSON.parse(owner.departmentQuestion),
          };
        });
        if (!this.formData.groupName) {
          this.baseOwner = this.allOwner;
        } else {
          this.baseOwner = this.allOwner.filter((owner) => {
            return owner.groupName === this.formData.groupName;
          });
        }
        showDataOk();
      } catch (error) {
        showDataNg(error);
      }
    },
    async upload(event) {
      try {
        let workbook = await getWorkbook(event.file);
        let worksheet = getWorksheet(workbook, "业主表");
        if (!worksheet) {
          this.$message({
            message: "工作表不正确",
            type: "error",
          });
          return;
        }
        let allRow = getAllRow(worksheet);
        allRow = _.chunk(allRow, 1000);
        await uploadOwner({ list: allRow });
        showUploadOk();
        await this.getOwnerByPaginationAndQuestion();
      } catch (error) {
        showUploadNg(error);
      }
    },
    async remove(row) {
      try {
        await removeOwnerByUuid(row);
        showRemoveOk();
        await this.getOwnerByPaginationAndQuestion();
      } catch (error) {
        showRemoveNg(error);
      }
    },
    edit(row) {
      this.$router.push({ name: "EditOwner", query: row });
    },
    async getOwnerByPaginationAndQuestion() {
      try {
        this.loading = true;
        console.log(this.formData);
        let result = await getOwnerByPaginationAndQuestion({
          ...this.pagination,
          ...this.formData,
        });
        this.tableData = result.data.list;
        this.pagination.total = result.data.total;
        await flushPage(
          this.tableData,
          this.pagination,
          this.getOwnerByPaginationAndQuestion
        );
      } catch (error) {
        showFlushNg(error);
      } finally {
        this.loading = false;
      }
    },
    create() {
      this.$router.push({ name: "CreateOwner" });
    },
    async search() {
      await this.getOwnerByPaginationAndQuestion();
    },
    async paginationChange(currentPage) {
      this.pagination.currentPage = currentPage;
      await this.getOwnerByPaginationAndQuestion();
    },
  },
  data() {
    return {
      baseOwner: [],
      allMonth: [],
      allOwner: [],
      loading: false,
      tableData: [],
      tableColumnList: [
        {
          label: "序号",
          type: "index",
          width: "100px",
        },
        {
          label: "姓名",
          prop: "name",
          width: "100px",
        },
        {
          label: "组团",
          prop: "groupName",
        },
        {
          label: "路址",
          prop: "address",
        },
        {
          label: "房屋类型",
          prop: "homeType",
        },
        {
          label: "房屋状态",
          prop: "homeStatus",
        },
        {
          label: "业主类别",
          prop: "ownerType",
        },
        {
          label: "是否装修",
          prop: "decorationStatus",
        },
        {
          label: "是否常住",
          prop: "liveStatus",
        },
        {
          label: "是否欠费",
          prop: "oweStatus",
        },
        {
          label: "缴费习惯",
          prop: "payStyle",
        },
        {
          label: "缴费月份",
          prop: "payMonth",
        },
        {
          label: "主键",
          prop: "uuid",
        },
        {
          label: "操作时间",
          prop: "opDatetime",
        },
        {
          label: "操作",
          width: "150px",
        },
      ],
      questionConfig: [],
      formData: {
        uuid: "",
        name: "",
        groupName: "",
        address: "",
        homeType: "",
        homeStatus: "",
        decorationStatus: "",
        liveStatus: "",
        oweStatus: "",
        ownerType: "",
        payStyle: "",
        payMonth: [],
        departmentQuestion: [[]],
        ownerQuestion: "",
      },
      controlList: [],
      pagination: {
        pageSize: 20,
        currentPage: 1,
        total: 0,
      },
    };
  },
};
</script>
